/*
 *  Copyright 2011 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.opu.vcforms.dtseditor;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.ByteArrayInputStream;
import java.io.Console;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import static javax.swing.JSplitPane.HORIZONTAL_SPLIT;
import static javax.swing.JSplitPane.VERTICAL_SPLIT;
import org.opu.vcforms.template.TxtTemplate;
import org.opu.vcforms.template.util.ArchiveUtil;
import org.opu.vcforms.transform_t2d.util.DocxUtil;
import org.opu.vcforms.vcapi.VcApi;
import org.opu.vcforms.vcapi.dao.VcTextTemplateDao;
import org.opu.vcforms.vcapi.domain.VcTextTemplate;
import org.springframework.beans.BeansException;

/**
 *
 * @author yura
 */
public class Window extends JFrame {

    private DefaultListModel lm = new DefaultListModel();
    private JList list = new JList(lm);
    private HelpPanel helpPanel;
    private TemplatePanel rightPane;
    private VcApi dataSource;

    public Window(VcApi dataSource) {
        super("onpu.doc_templates editor");
        this.dataSource = dataSource;
        refreshList(dataSource);
        initComponent();
    }

    private void refreshList(VcApi dataSource) throws BeansException {
        setData(dataSource.getVcTextTemplateDao().getList());
    }

    private void initComponent() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setSize(640, 480);

        JPanel leftPanel = initLeft();

        rightPane = new TemplatePanel(helpPanel);

        JSplitPane sp = new JSplitPane(HORIZONTAL_SPLIT, leftPanel, rightPane);
        sp.setResizeWeight(0.3);
        sp.setDividerSize(3);

        initPanelActions();
        
        list.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent me) {
                if (2 == me.getClickCount()) {
                    selectAction();
                }
            }
        });

        getContentPane().add(sp);
    }

    private JPanel initLeft() {
        Box h = Box.createHorizontalBox();
        h.add(Box.createVerticalStrut(4));
        h.add(Util.initBtn(new JButton(new AbstractAction("Add") {

            @Override public void actionPerformed(ActionEvent ae) {
                lm.addElement(new ViewTemplate(new VcTextTemplate(), "new template"));
            }
        })));
        h.add(Box.createVerticalStrut(4));
        h.add(Util.initBtn(new JButton(new AbstractAction("Refresh") {

            @Override public void actionPerformed(ActionEvent ae) {
                refreshList(dataSource);
            }
        })));
        h.add(Box.createVerticalStrut(4));
        h.add(Util.initBtn(new JButton(new AbstractAction("Delet") {

            @Override public void actionPerformed(ActionEvent ae) {
                ViewTemplate val = (ViewTemplate) list.getSelectedValue();
                VcTextTemplate template = val.getTemplate();
                dataSource.getVcTextTemplateDao().delete(template);
                refreshList(dataSource);
            }
        })));
        h.add(Box.createVerticalStrut(4));

        final JPanel hPanel = new JPanel();
        final JSplitPane leftSplit = new JSplitPane(VERTICAL_SPLIT,
                new JScrollPane(list), hPanel);
        leftSplit.setDividerSize(3);

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(h, BorderLayout.SOUTH);
        panel.add(leftSplit, BorderLayout.CENTER);

        helpPanel = new HelpPanel(hPanel) {

            @Override public void setActive(boolean active) {
                hPanel.removeAll();
                if (!active) {
                    leftSplit.setResizeWeight(1);
                } else {
                    leftSplit.setResizeWeight(0.5);
                }
            }
        };

        helpPanel.disactived();  // By default it disactiveded

        return panel;
    }

    private void initPanelActions() {
        rightPane.getSave().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                try {
                    VcTextTemplateDao dao = dataSource.getVcTextTemplateDao();
                    try {
                        dao.saveOrUpdate(rightPane.getVcTextTemplate());
                    } catch (Exception e) {
                        dao.save(rightPane.getVcTextTemplate());
                    }
                    try {
                        refreshItem();
                    } catch (Exception ex) {
                        Util.niceEx(ex, "Can't refresh", "Try to refresh all list\n");
                    }
                } catch (Exception exception) {
                    Util.niceEx(exception, "Can't save");
                }
            }
        });
        rightPane.getRefresh().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                try {
                    refreshItem();
                } catch (Exception ex) {
                    Util.niceEx(ex, "Can't refresh", "Try to select item in list\n");
                }
            }
        });
        rightPane.getValidate().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                try {
                    ViewTemplate val = (ViewTemplate) list.getSelectedValue();
                    VcTextTemplate template = val.getTemplate();
                    VcTextTemplate get = dataSource.getVcTextTemplateDao().get(template.getId());
                    if (get.getDocType() == 'X') {
                        TxtTemplate t = new TxtTemplate();
                        t.load(new ByteArrayInputStream(get.getFileContent()));
                        JOptionPane.showMessageDialog(null, "Validated");
                    } else if (get.getDocType() == 'T') {
                        Map<String, byte[]> archive = new ArchiveUtil()
                                .readArchive(new ByteArrayInputStream(get.getFileContent()));

                        if(new DocxUtil().documents(archive).isEmpty()){
                            throw new NullPointerException("no 'word/document.xml'");
                        }

                        JOptionPane.showMessageDialog(null, "Validated");
                    } else {
                        JOptionPane.showMessageDialog(null, "Unsuporte validation");
                    }
                } catch (Exception ex) {
                    Util.niceEx(ex, "Not valid", "Not valid\n");
                }
            }
        });
        rightPane.getUpload().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                try {
                    JFileChooser chooser = new JFileChooser();
                    if (chooser.showOpenDialog(Window.this) == JFileChooser.APPROVE_OPTION) {
                        byte[] data = Util.read(chooser.getSelectedFile());
                        rightPane.setContent(data);
                    }
                } catch (Exception ex) {
                    Util.niceEx(ex, "Not valid file");
                } catch (Error error) {
                    Util.niceEx(error, "Error hapen", "\nRestart the application !!!\n");
                }
            }
        });
    }

    public void refreshItem() throws BeansException {
        ViewTemplate val = (ViewTemplate) list.getSelectedValue();
        VcTextTemplate template = val.getTemplate();
        VcTextTemplate get = dataSource.getVcTextTemplateDao().get(template.getId());
        val.setTemplate(get);
        val.setName(get.getFileName());
        list.revalidate();
        selectAction();
    }

    private void selectAction() {
        ViewTemplate val = (ViewTemplate) list.getSelectedValue();
        VcTextTemplate template = val.getTemplate();
        try {
            System.console().format("select " + template);
        } catch (Exception e) {
            System.out.println("select " + template);
        }
        rightPane.setVcTextTemplate(template);
    }

    final void setData(List<VcTextTemplate> list) {
        lm.removeAllElements();
        for (VcTextTemplate t : list) {
            lm.addElement(new ViewTemplate(t, t.getFileName()));
        }
    }
}
